package com.big.tree.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author big tree
 */
@Configuration
public class DataSourceConfig {
    Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    @Bean("masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DruidDataSource masterDataSource() {
        logger.info("初始化数据库master链接");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("salveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.salve")
    public DruidDataSource slaveDataSource() {
        logger.info("创建 slave 数据库链接");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource primaryDataSource(@Autowired @Qualifier("masterDataSource") @Lazy DataSource masterDataSource,
                                        @Autowired @Qualifier("salveDataSource") @Lazy DataSource salveDataSource) {
        Map<Object, Object> map = new HashMap<>();
        map.put("master", masterDataSource);
        map.put("salve", salveDataSource);
        RoutingDataSource routingDataSource = new RoutingDataSource();
        routingDataSource.setTargetDataSources(map);
        routingDataSource.setDefaultTargetDataSource(masterDataSource);
        return routingDataSource;
    }
}

